/*
 * Copyright (C) 2015 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sj.uabrowser.net.converter;

import com.google.gson.TypeAdapter;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.net.BaseResponseNewBean;
import com.sj.uabrowser.net.exception.NetworkRequestException;
import com.sj.uabrowser.net.exception.TokenInvalidException;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseNewBodyConverter<T> implements Converter<ResponseBody, Object> {

    private final TypeAdapter<T> adapter;

    GsonResponseNewBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public Object convert(ResponseBody value) throws IOException {
        try {
            if(value==null)return null;
            T t = adapter.fromJson(value.charStream());
            if (t instanceof BaseResponseNewBean) {
                BaseResponseNewBean baseResponseBean = (BaseResponseNewBean) t;
                if (baseResponseBean.code == 200) {
                    if (baseResponseBean.data != null)
                        return baseResponseBean.data;
                    else return baseResponseBean;
                } else if (baseResponseBean.code == 1002 || baseResponseBean.code == 1004) {
                    throw new TokenInvalidException();
                } else {
                    throw new NetworkRequestException(baseResponseBean.code + "：" + baseResponseBean.errmsg);
                }

            } else {
                if (t != null)
                    Logger.e("T t:" + t.toString());
                else Logger.e("T t: is null");
                return null;
            }
        } finally {
            value.close();
        }
    }
}
